*** Run Synthetic controls on fit lead/lags
*** forward shift only

cd /disk/agedisk3/medicare.work/poterba-DUA52260/jetson-dua52260/botox/synth/100pct/robustness/forwardonly
use /disk/agedisk3/medicare.work/poterba-DUA52260/jetson-dua52260/botox/synth/100pct/growthgroupspanel.dta, clear 

*** Botox payments
format dt %tm_Mon_YY
*twoway scatter pmt_amt dt if group == 999, xline(569)  graphregion(color(white)) ylab(#3, format(%13.0fc)) yscale(range(0 1700000)) ylab(0 500000 1000000 1500000) ytitle("$/Month") xtitle("Month") xscale(range(504 668)) xlab(504 528 552 569 588 612 636 660)

*** Merge leads and lags
merge m:1 group using groupleadlags.dta
drop _merge mindistance

*** Can make a synth table here to see lags of those with heighest weight
** preserve
** keep if hcpcs_cd == (FILL IN)
**  keep hcpcs_cd group period
** duplicates drop

** Store group levels in macro
levelsof group, local(levels)


*** Replace generate with fitted lead/lags
tsset group dt
sort group dt
gen out = .


foreach g of local levels{
	disp `g'
	* Treated group gets no time shift
	if `g' == 999{
		replace out = pmt_amt if group == `g'
		continue
		}

	** Grab the stored shifter 
	qui summarize period if group == `g'
	local shift = r(min)

	** If positive, create lead 
		* Vestigial
	if `shift' > 0{
		replace out = F`shift'.pmt_amt if group == `g'
	}
	** If negative, create lag 
	if `shift' < 0{
		local shiftvalue = abs(`shift')
		replace out = L`shiftvalue'.pmt_amt if group == `g'
	}

	if `shift' == 0{
		replace out = pmt_amt if group == `g'
	}
}


** Cut missing data from front of time series
** Which is limited by the highest lag 
** Data start in 02
summarize period
drop if dt < mofd(mdy(1,1,2002)) + abs(r(min))

*** Cut missing data from end of time series
*** Which is limited by furthest lead
*** Data end 9/1/2015 because of second DRG change
** Vestigial
summarize period
drop if dt > mofd(mdy(9, 1, 2015)) - abs(r(max))


*** Filing date
disp mofd(mdy(6,5,2007))


**** Run Synthetic Controls
log using synth.log, replace
synth out out, trunit(999) trperiod(569) figure
log close 

************************************
************************************
*** Store fitted values
matrix fit = e(Y_synthetic)
keep if group == 999
svmat fit 
save synth_fit.dta, replace


